package com.ly.nethub.state

import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.content.Context
import android.os.Bundle
import java.util.concurrent.CopyOnWriteArrayList

interface AppStateObserver {
    fun onBackground()

    fun onForeground()
}


object AppStateManager : ActivityLifecycleCallbacks {
    private val mObserver = CopyOnWriteArrayList<AppStateObserver>()

    private var isCallbackRegister = false

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {
        notifyObserver(foreground = true)
    }

    override fun onActivityPaused(activity: Activity) {
        notifyObserver(foreground = false)
    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {

    }

    fun registerObserver(context: Context, observer: AppStateObserver) {
        if (mObserver.contains(observer)) return
        if (mObserver.isEmpty() || !isCallbackRegister) {
            if (context is Application) {
                context.registerActivityLifecycleCallbacks(this)
                isCallbackRegister = true
            } else {
                (context.applicationContext as? Application)?.let {
                    it.registerActivityLifecycleCallbacks(this)
                    isCallbackRegister = true
                }
            }
        }
        mObserver.add(observer)
    }

    fun unregisterObserver(context: Context, observer: AppStateObserver) {
        if (!mObserver.contains(observer)) return
        mObserver.remove(observer)
        if (mObserver.isEmpty()) {
            if (context is Application) {
                context.unregisterActivityLifecycleCallbacks(this)
                isCallbackRegister = false
            } else {
                (context.applicationContext as? Application)?.let {
                    it.unregisterActivityLifecycleCallbacks(this)
                    isCallbackRegister = false
                }
            }

        }
    }


    private fun notifyObserver(foreground: Boolean) {
        mObserver.forEach {
            if (foreground) {
                it.onForeground()
            } else {
                it.onBackground()
            }
        }
    }
}